package com.web.hotel.action;

import com.util.BaseActionUtil;
import com.util.DateUtil;
import com.util.JsonUtil;
import com.web.hotel.po.Dictionary;
import com.web.hotel.po.Hotel;
import com.web.hotel.service.DictionaryService;
import com.web.hotel.service.HotelService;
import com.web.hotel.vo.HotelVo;
import com.web.system.po.UserPo;
import org.apache.commons.io.IOUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.io.*;
import java.util.*;

@Controller
@Scope("prototype")
@ParentPackage(value = "struts-default")
@Namespace(value = "/")
@Action(value = "hotelAction",results={
        @Result(name="index", location="/jsp/hotel/hotel_list.jsp"),
        @Result(name="addPage", location="/jsp/hotel/hotel_add.jsp"),
})
public class HotelAction extends BaseActionUtil {

    private Hotel hotel;
    @Resource(name = "hotelService")
    private HotelService hotelService;
    @Resource(name = "dictionaryService")
    private DictionaryService dictionaryService;
    private HotelVo hotelVo;
    /**
     * 用于获取文件的数据流
     */
    private File[] picture;
    /**
     * 用于获取文件的文件名称(控件名称+FileName)
     */
    private String[] pictureFileName;
    /**
     * 用于获取文件的类型
     */
    private String[] pictureContentType;



    public String listGrid() throws Exception {
        Map<String, Object> dataMap = hotelService.listGrid(request);
        JsonUtil.jsonOut(dataMap);
        return NONE;
    }

    public String deleteHotelById() throws Exception {

        Map<String, Object> dataMap = new HashMap<String, Object>();

        String hotelIds = request.getParameter("ids");
        if(hotelIds == null || "".equals(hotelIds)){
            dataMap.put("flag", false);
            dataMap.put("msg", "服务端未接收到客户端传递的数据");
        }else{
            dataMap = hotelService.deleteHotelById(hotelIds);
        }
        String jsonStr = JsonUtil.objectToStr(dataMap);
        System.out.println(jsonStr);
        out.print(jsonStr);
        out.flush();
        out.close();
        return NONE;
    }

    public String addHotel() throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if(hotel == null || "".equals(hotel)){
            dataMap.put("flag", false);
            dataMap.put("msg", "服务端未接收到客户端传递的数据");
        }else{
            UserPo user = (UserPo)session.getAttribute("user");
            String createUser;
            if(user != null && !"".equals(user)){
                createUser = user.getUserName();
                Date createTime = new Date();
                hotel.setHotelImg(savePicture());
                hotel.setCreateTime(createTime);
                hotel.setCreateUser(createUser);
                dataMap = hotelService.addHotel(hotel);
            }else{
                dataMap.put("flag", false);
                dataMap.put("msg", "服务端未接收到客户端传递的数据");
            }
        }
        String jsonStr = JsonUtil.objectToStr(dataMap);
        System.out.println(jsonStr);
        out.print(jsonStr);
        out.flush();
        out.close();
        return NONE;
    }

    public String editHotel() throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if(hotelVo == null){
            dataMap.put("flag", false);
            dataMap.put("msg", "服务端未接收到客户端传递的数据");
        }else{
            //酒店信息更新先从数据库查询，在更新，这里先不做了
            hotelVo.setHotelImg(savePicture());
            dataMap = hotelService.editHotel(hotelVo);
        }
        JsonUtil.jsonOut(dataMap);
        return NONE;
    }

    public String getHotelType() throws Exception{
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        //这里从字典树获取
        List<Dictionary> dictionaryList = dictionaryService.getDictionaryByDicName("sys_hotel_type");
        for(Dictionary dictionary:dictionaryList){
            Map<String, Object> hotelType = new HashMap<String, Object>();
            hotelType.put("hotelType", dictionary.getDicValue());
            result.add(hotelType);
        }
        JsonUtil.jsonOut(result);
        return NONE;
    }

    public String getHotelById() throws Exception{
        Map<String, Object> dataMap = new HashMap<String, Object>();
        String hotelId = request.getParameter("hotelId");
        if(hotelId == null || "".equals(hotelId)){
            dataMap.put("flag", false);
            dataMap.put("msg", "服务端未接收到客户端传递的数据");
        }else{
            Integer int_hotelId = Integer.parseInt(hotelId);
            HotelVo hotelI = hotelService.getHotelVoById(int_hotelId);
            dataMap.put("flag", true);
            dataMap.put("msg", hotelI);
        }
        JsonUtil.jsonOut(dataMap);
        return NONE;
    }

    public String getHotelName() throws Exception{
        String hotelName = request.getParameter("q");
        List<Hotel> hotelList = hotelService.getAllHotelByName(hotelName);
        String jsonStr = JsonUtil.objectToStr(hotelList);
        System.out.println(jsonStr);
        out.print(jsonStr);
        out.flush();
        out.close();
        return NONE;
    }



    public String getHotelByCityName() throws Exception{
        String cityName = request.getParameter("q");
        List<Hotel> hotelList = hotelService.getAllHotelByCityName(cityName);
        String jsonStr = JsonUtil.objectToStr(hotelList);
        System.out.println(jsonStr);
        out.print(jsonStr);
        out.flush();
        out.close();
        return NONE;
    }
    //文件保存到服务器上
    private String savePicture() throws IOException{
        /**
         * 服务器上的文件绝对路径
         */
        String ImagePath = "http://" + request.getServerName() //服务器地址
                + ":"
                + request.getServerPort()           //端口号
                + request.getContextPath()     //项目名称
                + "/image";

        String upload_filename = "";
        String upload_filepath = "";
        String upload_path ="";
        if (this.pictureFileName != null && !this.pictureFileName.equals("")) {
            for (int i = 0; i < picture.length; i++) {
                /**
                 * 获得文件输入流
                 */
                InputStream inputStream = new FileInputStream(this.picture[i]);
                /**
                 * 获取上传文件的的存放路径。
                 */
                upload_path = this.servletContext.getRealPath("/image");
                /**
                 * 判断路径是否存在，不存在则创建文件夹
                 */
                File file = new File(upload_path);
                if (!file.exists()) {
                    file.mkdirs();
                }
                /**
                 * 防止文件重复修改文件名，加上日期
                 */
                upload_filepath = DateUtil.getTimeStamp() + "_" + this.pictureFileName[i];
                OutputStream outputStream = new FileOutputStream(upload_path + "/" + upload_filepath);
                int result = IOUtils.copy(inputStream, outputStream);
                IOUtils.closeQuietly(inputStream);
                IOUtils.closeQuietly(outputStream);
            }
        }
        return ImagePath + "/" + upload_filepath;
    }

    public String execute() throws Exception {
        return null;
    }

    public String index(){
        return "index";
    }

    public String addPage(){
        return "addPage";
    }

    public File[] getPicture() {
        return picture;
    }

    public void setPicture(File[] picture) {
        this.picture = picture;
    }

    public String[] getPictureFileName() {
        return pictureFileName;
    }

    public void setPictureFileName(String[] pictureFileName) {
        this.pictureFileName = pictureFileName;
    }

    public String[] getPictureContentType() {
        return pictureContentType;
    }

    public void setPictureContentType(String[] pictureContentType) {
        this.pictureContentType = pictureContentType;
    }

    public Hotel getHotel() {
        return hotel;
    }

    public HotelVo getHotelVo() {
        return hotelVo;
    }

    public void setHotelVo(HotelVo hotelVo) {
        this.hotelVo = hotelVo;
    }

    public void setHotel(Hotel hotel) {
        this.hotel = hotel;
    }
}
